package com.zxb.base.monitor.vo;


import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zxb.base.monitor.util.LayoutUtil;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Accessors;

import java.time.LocalDateTime;
import java.util.List;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_FORMATTER;

/**
 * @author Zxb
 */
@Data
@Builder
@Accessors(chain = true)
public class Jvm {
    /**
     * 虚拟机名称
     */
    private String vmName;

    /**
     * JDK版本
     */
    private String jdkVersion;

    /**
     * JavaHome
     */
    private String javaHome;

    /**
     * 进程号
     */
    private String pid;

    /**
     * 启动时间
     */
    private LocalDateTime startTime;

    /**
     * 运行时长
     */
    private long runtime;

    /**
     * 启动参数
     */
    private List<String> startParameters;

    @Override
    public String toString() {
        return LayoutUtil.Table.of(
                LayoutUtil.Row.of("VM Name", vmName),
                LayoutUtil.Row.of("JDK Version", jdkVersion),
                LayoutUtil.Row.of("Java Home", javaHome),
                LayoutUtil.Row.of("PID", pid),
                LayoutUtil.Row.of("StartTime", NORM_DATETIME_FORMATTER.format(startTime)),
                LayoutUtil.Row.of("RunTime", DateUtil.formatBetween(runtime, BetweenFormatter.Level.SECOND)
                        .replaceAll(BetweenFormatter.Level.SECOND.getName(), "s")
                        .replaceAll(BetweenFormatter.Level.MINUTE.getName(), "m")
                        .replaceAll(BetweenFormatter.Level.HOUR.getName(), "h")
                        .replaceAll(BetweenFormatter.Level.DAY.getName(), "d")),
                LayoutUtil.Row.of("Start Parameters", startParameters.size(), startParameters)
        ).toString();
    }

    public JSONArray toJSON() {
        JSONArray ja = new JSONArray();
        JSONObject jo = new JSONObject();
        jo.put("vmName", vmName);
        jo.put("jdkVersion", jdkVersion);
        jo.put("javaHome", javaHome);
        jo.put("pid", pid);
        jo.put("startTime", NORM_DATETIME_FORMATTER.format(startTime));
        jo.put("runTime", DateUtil.formatBetween(runtime, BetweenFormatter.Level.SECOND)
                .replaceAll(BetweenFormatter.Level.SECOND.getName(), "s")
                .replaceAll(BetweenFormatter.Level.MINUTE.getName(), "m")
                .replaceAll(BetweenFormatter.Level.HOUR.getName(), "h")
                .replaceAll(BetweenFormatter.Level.DAY.getName(), "d"));
        jo.put("startParameters", startParameters);
        ja.add(jo);
        return ja;
    }
}
